#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>


static void Usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << "serverIP serverPort" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    uint16_t sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        std::cerr << "Create Socket Fail!" << std::endl;
        exit(2);
    }

    std::string serverIP = argv[1];
    uint16_t serverPort = atoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverPort);
    server.sin_addr.s_addr = inet_addr(serverIP.c_str());

    if(connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
    {
        std::cerr << "Connet Fail!" << std::endl;
        exit(3);
    }

    std::cout << "Connet Success!" << std::endl;
    while(true)
    {
        std::string message;
        std::cout << "Please Enter Your Message: ";
        std::getline(std::cin, message);
        send(sock, message.c_str(), message.size(), 0);
        char buffer[1024];
        ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
        if(s > 0)
        {
            buffer[s] = 0;
            std::cout << "server# " << buffer << std::endl;
        }
        else if(s == 0)
            break;
        else
            break;
    }
    close(sock);

    return 0;
}